<template>
	<view class="content">
		<view class="qaa-item qaa-thumb" v-if="bodyShow">
			<view class="qaa-headicon">
				<image :src="systemLogo" mode="widthFix"></image>
			</view>
			<view class="qaa-item-content" v-if="bannerSrc">
				<view class="qaa-item-ct">
					<image :src="bannerSrc" mode="widthFix"></image>
				</view>
			</view>
		</view>
		<view class="qaa-item qaa-hello" v-if="bodyShow">
			<view class="qaa-headicon">
				<image :src="systemLogo" mode="widthFix"></image>
			</view>
			<view class="qaa-item-content">
				<view class="qaa-start-desc" v-if="desc">
					<text>{{desc}}</text>
				</view>
				<!-- #ifdef MP-QQ||MP-WEIXIN -->
				<view class="qaa-start-btn" @click="startAction" v-if="isAuthUserInfo">
					<text>开始测试</text>
				</view>
				<button open-type="getUserInfo" class="qaa-start-btn" @getuserinfo="userInfoAction" v-else>
					<text>请授权测试</text>
				</button>
				<!-- #endif -->
				
				<!-- #ifdef MP-TOUTIAO -->
				<view class="qaa-start-btn" @click="startAction" v-if="isAuthUserInfo && isPay">
					<text>开始测试</text>
				</view>
				<button class="qaa-start-btn" @click="orderPayByTt" v-else-if="isAuthUserInfo && !isPay">
					<text>请支付{{payPrice}}元参与测试</text>
				</button>
				<button open-type="getUserInfo" class="qaa-start-btn" @click="getTtUserInfo" v-else>
					<text>请授权测试</text>
				</button>
				<!-- #endif -->
			</view>
		</view>
		
		<view class="qaa-item-right" v-if="isStart">
			<view class="qaa-itemr-content">
				<view class="qaa-item-ct">
					<text class="qaa-can-start">开始测试</text>
				</view>
			</view>
			<view class="qaa-itemr-headicon">
				<image :src="userInfo.avatarUrl" mode="widthFix"></image>
			</view>
		</view>

		<view class="list">
			<UserDialog :index="item.index" :type="item.type" :info="item" v-for="(item, index) in list"
			 :key="item.topic_id" :user-info="userInfo" :system-logo="systemLogo" :selfIndex="index" :currentIndex="currentIndex"/>
		</view>
		<Result :step="resultStep" :src="poster.src" :system-logo="systemLogo"/>
		<view class="footer-padding" v-if="resultStep == 1"></view>
		<view class="footer" v-if="resultStep == 1">
			<button open-type="share" id="btn-share">
				<image src="../../static/icon-share1.png" mode="widthFix"></image>
				<text>叫人来测</text>
			</button>
			<!-- #ifdef MP-TOUTIAO||MP-WEIXIN -->
			<view @click="redirectMoreTopic">
				<image src="../../static/icon-share2.png" mode="widthFix"></image>
				<text>更多测试</text>
			</view>
			<!-- #endif -->
			<!-- #ifdef MP-QQ -->
			<view @click="shareWithQQZone">
				<image src="../../static/icon-share2.png" mode="widthFix"></image>
				<text>发到说说</text>
			</view>
			<!-- #endif -->
		</view>
		<view :class="['mask', shareVisible ? 'active' : '']">
			<view class="mask-touch"></view>
			<view class="mask-content">
				<view class="mask-user">
					<image src="../../static/mask-bg.png" mode="widthFix" class="mask-user-bg"></image>
					<view class="mask-user-content">
						<view class="mask-user-img">
							<image :src="userInfo.avatarUrl" mode="widthFix"></image>
						</view>
						<view><text>Hi,{{userInfo.nickName}}, 测评你发现不一样的事物</text></view>
					</view>
				</view>
				<view class="mask-btns">
					<button v-if="shareType == 2" class="mask-btn" @click="showVideo"><text>看广告后查看详细结果</text></button>
					<button v-else id="btn-mask-share" class="mask-btn" open-type="share"><text>分享后查看详细结果</text></button>
				</view>
			</view>
		</view>
		<view :class="['auth-pu', authPanelVisible ? 'active' : '']">
			<view class="auth-pu-content">
				<view class="auth-pu-text">
					<text>保存图片需要授权相册，请允许授权</text>
				</view>
				<button class="auth-pu-confirm" open-type="openSetting" @opensetting="openSettingAction">
					<text>确定</text>
				</button>
			</view>
		</view>
		<view class="poster-content">
			<canvas canvas-id="posterCanvas" class="posterCanvas" :style="{width: `${poster.width}px`,
					 height: `${poster.height}px`
			}"></canvas>
		</view>
		<ActionSheet :visible="actionSheetVisible" @cancel="openActionSheetAction(false)">
			<view slot="actionsheet-child">
				<view class="actionsheet-item">
					<button open-type="share" share-type="1"><text>发送给好友</text></button>
				</view>
				<!-- #ifdef MP-QQ -->
				<view class="actionsheet-item" @click="shareWithQQZone">
					<text>分享到说说</text>
				</view>
				<!-- #endif -->
				<view class="actionsheet-item" @click="savePoster">
					<text>保存图片</text>
				</view>
			</view>
		</ActionSheet>
		<Loading text="正在为你分析结果，请耐心等待" :visible="progressVisible" :progress="progress" />
	</view>
</template>

<script>
	import config from '../../src/config/api.config.js';
	import utils from '../../src/utils/utils.js';
	import userCheck from '../../src/utils/user.js';
	import request from '../../src/utils/request.js';
	import UserDialog from './user-dialog.vue';
	import Result from './result.vue';
	import Loading from '../../src/components/loading.vue';
	import ActionSheet from '../../src/components/actionSheet.vue';

	
	// 在页面中定义激励视频广告
	let videoAd = null
	
	// #ifdef MP-TOUTIAO
	const info = tt.getSystemInfoSync();
	if (info.appName.toUpperCase() === 'DOUYIN') {
		videoAd = tt.createRewardedVideoAd({
		    adUnitId: '958j06jk73ilaohdti'
		});
	}
	// #endif
	
	export default {
		data() {
			return {
				id: '',
				dTitle:'',
				parentOpenid:'',//进入页面获取是否链接带有其他人的openid
				openid: '',
				isAuthUserInfo: false, // 是否授权
				userInfo: null, // 用户信息
				systemInfo: {
					windowWidth: 0,
					windowHeight: 0
				}, // 系统信息
				poster: {
					width: 0,
					height: 0,
					src: ''
				}, // 海报信息
				title: '',
				desc: '',
				bannerSrc: '',
				listSource: [], // 数据源，题目
				list: [], // 列表内容
				result: [], // 选择结果
				currentIndex: 0, // 当前做的题目索引
				isStart: false, // 是否已经开始
				isFinish:false,//是否已经做完题目
				shareMsg: {
					title: '', // 分享标题
					img: '', // 分享海报底图原图
					preImg: '', // 海报生成之前分享的图片
					shuoshuo: '', // 分享说说标题
					logo: { // 头像数据
						side_length: 0, // 头像直径
						x: 0, // 头像横坐标
						y: 0, // 头像纵坐标
						type: 1 // 头像类型 1 圆形 2 方形
					},
					qrcode: { // 二维码数据
						side_length: 0, // 二维码直径
						x: 0, // 二维码横坐标
						y: 0, // 二维码纵坐标
					},
					nickName: { // 昵称数据
						color: "", // 昵称颜色
						description: "", // 昵称内容
						size: 0, // 昵称大小
						x: 0, // 昵称横坐标
						y: 0 // 昵称纵坐标
					},
					weixin_qrcode: '', //微信二维码
					qq_qrcode: '', //QQ二维码
					tt_qrcode: '', //头条二维码
				},
				share_qrcode: '', //分享二维码
				shareVisible: false, // 分享可视化
				authPanelVisible: false, // 相册授权面板可视化
				actionSheetVisible: false, // 长按弹窗可视化
				isNeedToShare: false, // 是否需要强制分享才能显示海报
				shareType: 1, //分享类型 0-直接显示 1-分享 2-看广告 3-支付
				resultStep: -1, // 分析结果步骤
				timer: null,
				progressTimer: null,
				progressOverTimer: null,
				progressVisible: false, // 合成图片进度可视化
				progress: 0, // 合成图片进度
				localtionPlatform: 1, //当前设备 1-qq 2-微信 3-抖音，后面继续增加
				use_RewardedVideoAd: true, //是否激励广告使用 false-不可以 true-可以
				payPrice: 0, //测评支付费用
				isPay: false, //是否已支付
				bodyShow: false ,// 显示页面
				systemLogo: '', // 系统头像
				tt_share_template_id:'',//头条分享id
				user_can_see_ad:true,//用户可以正常看广告
				
			}
		},
		onLoad(options) {
			uni.showLoading();
			// 检测是否登录过期
			const that = this;

			uni.showNavigationBarLoading();
			this.id = options.id;
			this.parentOpenid = options.parentOpenid != undefined ?options.parentOpenid:'';

			// 注册子组件选择完成
			uni.$on('subjectFinsh', this.subjectFinshAction);
			// 注册子组件重做上一题
			uni.$on('subjectAgain', this.subjectAgainAction);
			// 长按保存分享图片
			uni.$on('openActionSheet', this.openActionSheetAction);

			// 获取系统信息
			this.systemInfo = utils.systemInfo();

			// 查看用户是否授权用户信息
			uni.getSetting({
				success: (r) => {
					console.log(r)
					// 如果已经授权了
					if (r.authSetting['scope.userInfo']) {
						this.isAuthUserInfo = true;
						uni.getUserInfo({
							success: (ur) => {
								this.userInfo = ur.userInfo;
							}
						})
					}
				}
			});
			
			
			// #ifdef MP-WEIXIN
			// 微信小程序设置分享配置
			wx.showShareMenu({
				// shareTicket 是获取转发目标群信息的票据，只有拥有 shareTicket 才能拿到群信息，用户每次转发都会生成对应唯一的shareTicket 。
				withShareTicket: true,
			});
			
			
			// 在页面onLoad回调事件中创建激励视频广告实例
			if (wx.createRewardedVideoAd) {
			  videoAd = wx.createRewardedVideoAd({
			    adUnitId: 'adunit-bef89975a6410609'
			  })
			  videoAd.onLoad(() => {})
			  videoAd.onError((err) => {})
			  videoAd.onClose((res) => {
				  console.log('videoAd onClose', res)
				  if (res.isEnded) {
				  	console.log('观看完成')
					
					console.log('走广告分销功能')
					//走广告分销功能
					that.adDistribution();;
				  	// 关闭遮罩层
				  	that.shareVisible = false;
				  	that.resultStep = 1;
				  	that.scrollToBottom();
					
					// that.goToResultPage(that.shareMsg.img);
				  } else {
				  	console.log('半途而废')
				  
				  }
			  })
			}
			// #endif

			// #ifdef MP-TOUTIAO
			//判断当前设备，激励广告只能在抖音高版本里使用
			
			if (info.appName.toUpperCase() !== 'DOUYIN') {
				this.use_RewardedVideoAd = false
			}else{
				//可以看激励广告
				try{
					if(videoAd.closeFunc){
						videoAd.offClose(videoAd.closeFunc);
				    }
				} catch (e) {
				    console.warn("--------------videoAd.offClose error:");
				    console.error(e);
				}
				videoAd.closeFunc = function (res) {
				    // 用户点击了【关闭广告】按钮
				    // 小于基础库版本，res 是一个 undefined
				    console.warn("播放完毕",res);
					console.log("当前页面id："+that.id)
				    if (res && res.isEnded || res === undefined) {        // 正常播放结束，可以下发游戏奖励
				        console.log('可以下发奖励了')
						// 给予奖励
						console.log('观看完成')
						
						console.log('走广告分销功能')
						//走广告分销功能
						that.adDistribution();;
						
						// 关闭遮罩层
						that.shareVisible = false;
						that.resultStep = 1;
						that.scrollToBottom();
						
						// that.goToResultPage(that.shareMsg.img);
				    }
				};
				videoAd.onClose(videoAd.closeFunc);
			}
			// #endif
			
			console.log('父级id：'+this.parentOpenid)
			/**
			 * 统一处理页面获取用户openid操作
			 * @param {Object} openid
			 */
			this.localtionPlatform = userCheck.PlatformType;
			userCheck.checkSession(function(openid){
				that.openid = openid
				console.log('回调的openid:'+openid)
				//处理完数据后再做页面本身的处理
				// 获取页面数据
				that.getData();
				console.log('页面上获取的openid：'+that.openid)
			},that.parentOpenid);
			
		},
		
		onUnload() {
			uni.$off('subjectFinsh');
			uni.$off('subjectAgain');
			uni.$off('openActionSheet');
			this.timer && clearTimeout(this.timer);
			this.progressTimer && clearInterval(this.progressTimer);
			this.progressOverTimer && clearTimeout(this.progressOverTimer);
		},
		methods: {
			//跳转更多测试
			redirectMoreTopic(){
				uni.navigateTo({
					url: `/pages/search/index`
				})
			},
			// 获取页面数据
			async getData() {
				const r = await request({
					url: `${config.API}api/topic/details`,
					data: {
						topic_id: this.id,
						openid: this.openid
					}
				});
				uni.hideNavigationBarLoading();
				if (r.error_code === 0) {
					// #ifdef MP-QQ
					this.isNeedToShare = (r.data.need_share !== 0);
					this.shareType = r.data.need_share
					this.share_qrcode = r.data.qq_qrcode
					// #endif
					// #ifdef MP-WEIXIN
					this.isNeedToShare = (r.data.weixin_need_share !== 0);
					this.shareType = r.data.weixin_need_share
					this.share_qrcode = r.data.weixin_qrcode
					// #endif
					// #ifdef MP-TOUTIAO
					this.isNeedToShare = (r.data.tt_need_share !== 0);
					this.shareType = r.data.tt_need_share
					this.share_qrcode = r.data.tt_qrcode
					this.payPrice = r.data.tt_play_price
					if (r.data.tt_need_share != 3) {
						//不需要支付情况下，将支付状态改成已支付
						this.isPay = true;
					}
					// #endif
					this.dTitle = r.data.title;
					uni.setNavigationBarTitle({
						title: r.data.title
					});
					this.desc = r.data.description;
					this.bannerSrc = r.data.banner_img;
					this.shareMsg = {
						title: r.data.share_content,
						logo: r.data.headerimg_attr,
						nickName: r.data.nickname_attr,
						preImg: r.data.share_img,
						shuoshuo: r.data.share_shuoshuo,
						img: '',
						qrcode: r.data.qrcode_attr,
						qq_qrcode: r.data.qq_qrcode,
						weixin_qrcode: r.data.weixin_qrcode,
					};
					r.data.topic.topic_type.forEach((v, k) => {
						if (v == '2') {
							this.listSource.push({
								title: r.data.topic.topic_question[k],
								type: 3,
								index: k,
							});
						} else if (v == '3') {
							this.listSource.push({
								title: r.data.topic.topic_question[k],
								type: 2,
								index: k,
							});
						} else {
							if (r.data.topic.topic_question_img[k]) {
								this.listSource.push({
									title: r.data.topic.topic_question[k],
									type: 1,
									index: k,
									img: r.data.topic.topic_question_img[k],
									content: r.data.topic.topic_answer[k]
								});
							} else {
								this.listSource.push({
									title: r.data.topic.topic_question[k],
									type: 0,
									index: k,
									content: r.data.topic.topic_answer[k]
								});
							}
						}
					});
					this.systemLogo = r.data.system_logo;
					this.tt_share_template_id = r.data.tt_share_template_id
					
					this.user_can_see_ad = r.data.user_can_see_ad;
					
					
					this.bodyShow = true;
					uni.hideLoading();
					
				}
			},

			//授权后存储用户信息
			async saveUserInfo() {
				const r = await request({
					url: `${config.API}api/saveUserInfo`,
					data: {
						openid: this.openid,
						avatarUrl: this.userInfo.avatarUrl,
						nickName: this.userInfo.nickName
					},
				});
				console.log(r)
			},

			/**
			 * 下载大图任务
			 * @param {string} filepath 下载图片地址
			 * @param {Object} callback 下载成功回调
			 */
			downloadTask(filepath, callback) {
				console.log('下载大图任务')
				const that = this;
				this.progressVisible = true;
				const downloadTask = uni.downloadFile({
					url: filepath,
					success(r) {
						if (r.statusCode === 200 && r.errMsg === 'downloadFile:ok') {
							//区分不同端的图片处理
							// #ifdef MP-QQ || MP-WEIXIN
							downloadTask.offProgressUpdate(that.downloadAction);
							// #endif
							// #ifdef MP-TOUTIAO
							downloadTask.onProgressUpdate(that.downloadAction);
							// #endif
							callback && callback(r.tempFilePath);
						} else {
							uni.uni.showToast({
								title: '分析失败，图片下载失败'
							});
							this.progressVisible = false;
						}
					}
				});

				downloadTask.onProgressUpdate(this.downloadAction);
			},
			// 下载监听
			downloadAction(r) {
				this.progress = Math.ceil(r.progress * .8);
			},
			/**
			 * 绘制海报
			 * @param {Object} callback 回调
			 */
			drawPoster(callback) {
				console.log('开始绘制海报')
				const that = this;
				const ctx = uni.createCanvasContext('posterCanvas');
				// 转换底图分享图片地址为本地地址
				this.downloadTask(that.shareMsg.img, function(path) {
					let progress = 80;
					that.progressTimer = setInterval(function() {
						if (progress < 98) progress += 1;
						if (that.resultStep === 1) return;
						that.progress = progress;
					}, 200);
					
					uni.getImageInfo({
								
						src: path,
						success(r) {
							console.log('绘制开始成功')
							// 设置海报高度
							that.poster.width = r.width;
							that.poster.height = r.height;
							// 绘制背景底图
							ctx.drawImage(
								r.path,
								0, 0, that.poster.width, that.poster.height
							);
							ctx.save();

							//直接显示结果图
							that.progress = 100;
							that.progressTimer && clearInterval(that.progressTimer);
							that.progressOverTimer = setTimeout(function() {
								that.progressVisible = false;
								that.progress = 0;
							}, 500);
							callback && callback(path);
							
						},
						fail(err) {
							console.log(1234)
							that.createPosterFailAction();
						}
					});
				});
			},
			
			/**
			 * 打开长按菜单
			 * @param {Object} visible true: 显示 false: 隐藏
			 */
			openActionSheetAction(visible) {
				this.actionSheetVisible = visible;
			},
			
			// 用户信息回调
			userInfoAction(r) {
				// 如果用户拒绝授权
				if (r.detail.errMsg === 'getUserInfo:fail auth deny' || r.detail.errMsg === 'getUserInfo:fail authorize deny') {
					return uni.showToast({
						title: '请允许授权',
						icon: 'none'
					});
				}
				// 登录
				this.userInfo = r.detail.userInfo;
				this.isAuthUserInfo = true;
				this.isStart = true;
				//存储用户信息
				this.saveUserInfo();
				this.addOne();
			},

			// #ifdef MP-QQ
			// 分享说说
			shareWithQQZone() {
				// #ifdef MP-QQ
				return qq.openQzonePublish({
					text: this.shareMsg.shuoshuo,
					media: [{
						type: 'photo',
						path: this.resultStep === 1 ? this.poster.src : this.shareMsg.preImg
					}]
				});
				// #endif
				uni.showToast({
					title: '暂不支持分享到QQ空间',
					icon: 'none'
				})
			},
			// #endif
			// 生成海报失败
			createPosterFailAction() {
				uni.showToast({
					title: '分析生成失败',
					icon: 'none'
				});
				this.progressTimer && clearInterval(this.progressTimer);
				this.progressVisible = false;
			},
			// 滚动到页面底部
			scrollToBottom() {
				this.timer = setTimeout(() => {
					uni.pageScrollTo({
						duration: 300,
						scrollTop: 999999
					});
				}, 500);
			},
			// 子组件选择完
			async subjectFinshAction(r) {
				let _result = this.result;
				_result[this.currentIndex] = r;
				this.result = _result;
				this.currentIndex++;
				if (this.currentIndex <= this.listSource.length - 1) {
					this.addOne();
				} else {
					this.isFinish = true;
					// 整理结果数组转对象
					const _result = {};
					for (let i = 0, l = this.result.length; i < l; i++) {
						_result[i] = this.result[i];
					}
					const r = await request({
						url: `${config.API}api/topic/getImg`,
						method: 'post',
						data: {
							topic_id: this.id,
							openid: this.openid,
							platform:this.localtionPlatform,
							parentOpenid:this.parentOpenid,
							result: JSON.stringify(_result)
						}
					});
					console.log('请求参数')
					console.log({
							topic_id: this.id,
							openid: this.openid,
							result: JSON.stringify(_result)
						})
					console.log('响应结果')
					console.log(r)
					if (r.error_code === 0) {
						this.shareMsg.img = r.data.img;
						// 显示正在生成中...
						this.resultStep = 0;
						
						//旧版本在当前页显示结果数据
						this.drawPoster(path => {
							// #ifdef MP-QQ || MP-WEIXIN
							if (this.isNeedToShare && this.user_can_see_ad) {
								this.poster.src = path;
								this.timer = setTimeout(() => {
									this.shareVisible = true;
								}, 500);
							} else {
								this.poster.src = path;
								// 显示海报以及保存图片提示语
								this.resultStep = 1;
								this.scrollToBottom();
							}
							// #endif
							// #ifdef MP-TOUTIAO
							console.log('wawawawa')
							//头条输出结果的前提 分享或者看广告需要出弹窗，支付直接显示结果
							//看广告的前提是当前版本支持
							if (this.isNeedToShare && (this.shareType == 1 || this.shareType == 2)) {
								if (this.shareType == 2 && this.use_RewardedVideoAd && this.user_can_see_ad) {
									this.poster.src = path;
									this.timer = setTimeout(() => {
										this.shareVisible = true;
									}, 500);
								} else {
									this.poster.src = path;
									// 显示海报以及保存图片提示语
									this.resultStep = 1;
									this.scrollToBottom();
								}
							} else {
								this.poster.src = path;
								// 显示海报以及保存图片提示语
								this.resultStep = 1;
								this.scrollToBottom();
							}
							// #endif
							
							
						});
						
						//新版
						// //直接显示结果图
						// this.progress = 100;
						// this.progressVisible = false;
						// this.progress = 0;
						
						// //处理结果图片新页面跳转显示
						// console.log('进入跳转页面的步骤')
						// // #ifdef MP-QQ || MP-WEIXIN
						// if (this.isNeedToShare && this.user_can_see_ad) {
						// 	// this.poster.src = path;
						// 	this.timer = setTimeout(() => {
						// 		this.shareVisible = true;
						// 	}, 500);
						// } else {
						// 	this.goToResultPage(r.data.img);
						// }
						// // #endif
						// // #ifdef MP-TOUTIAO
						// //头条输出结果的前提 分享或者看广告需要出弹窗，支付直接显示结果
						// //看广告的前提是当前版本支持
						// if (this.isNeedToShare && (this.shareType == 1 || this.shareType == 2)) {
						// 	console.log('进入跳转111111111111页面的步骤')
						// 	if (this.shareType == 2 && this.use_RewardedVideoAd && this.user_can_see_ad) {
						// 		console.log('进入跳转2页面的步骤')
						// 		// this.poster.src = path;
						// 		this.timer = setTimeout(() => {
						// 			this.shareVisible = true;
						// 		}, 500);
						// 	} else {
						// 		console.log('进入跳转页面的步骤1111')
						// 		console.log(r.data.img)
						// 		this.goToResultPage(r.data.img);
						// 	}
						// } else {
						// 	console.log('进入跳转页面的步骤2222')
						// 	this.goToResultPage(r.data.img);
						// }
						// // #endif
					} else {
						uni.showToast({
							title: '题目数据提交失败'
						});
					}
				}
			},
			
			//新方法，答题完成跳转结果页面
			/**
			 * 跳转到结果页
			 * @param {Object} imgUrl 图片地址
			 */
			goToResultPage(imgUrl) {
				console.log('准备跳转页面')
				uni.navigateTo({
					url: `/pages/detail/imgshow?shareType=${this.shareType}&tt_share_template_id=${this.tt_share_template_id}&preImg=${this.shareMsg.preImg}&openid=${this.openid}&id=${this.id}&src=${encodeURIComponent(imgUrl)}&question=${this.dTitle}`
				})
			},
			//新方法，答题完成跳转结果页面
			
			// 子组件重做上一题
			subjectAgainAction(r) {
				this.currentIndex--;
				this.addOne();
			},
			// 开始游戏
			startAction() {
				if (this.isStart) return;
				this.isStart = true;
				this.addOne();
			},
			// 新增一题
			addOne() {
				this.list.push(this.listSource[this.currentIndex]);
				this.scrollToBottom();
			},
			// 打开授权设置回调
			openSettingAction(r) {
				this.authPanelVisible = false;
			},
			// 保存图片
			savePoster() {
				// #ifdef H5 || MP-ALIPAY
				return uni.showToast({
					title: '暂不支持保存',
					icon: 'none',
					duration: 2000
				})
				// #endif

				uni.saveImageToPhotosAlbum({
					filePath: this.poster.src,
					success(saveResult) {
						uni.showToast({
							title: '保存成功',
							icon: 'none'
						});
					},
					fail: failRes => {
						// 如果保存失败，是否没有授权
						if (failRes.errMsg === 'saveImageToPhotosAlbum:fail auth deny' || failRes.errMsg ===
							'saveImageToPhotosAlbum:fail authorize deny') {
							this.authPanelVisible = true;
						}
					},
					complete: () => {
						this.actionSheetVisible = false;
					}
				});
			},
			
			
			//看完广告后做广告分销入口函数
			async adDistribution() {
				console.log('进入处理分销广告逻辑')
				const r = await request({
					url: `${config.API}api/distribution/get`,
					method:'post',
					data: {
						openid: this.openid,
						topic_id:this.id
					},
				});
				console.log(r) 
			},

			// #ifdef MP-QQ
			//qq端-查看激励视频
			showVideo() {
				const that = this;
				let videoAd = qq.createRewardedVideoAd({
					adUnitId: '6f3056a035c51f7bf29ae9c622c3d0fa'
				})
				videoAd.onClose(function(res) {
					console.log('videoAd onClose', res)
					if (res.isEnded) {
						console.log('观看完成')
						// 关闭遮罩层
						that.shareVisible = false;
						that.resultStep = 1;
						that.scrollToBottom();
						
						// that.goToResultPage(that.shareMsg.img);
					} else {
						console.log('半途而废')

					}
				})
				videoAd.load().then(() => {
					console.log('激励视频加载成功');
					videoAd.show().then(() => {
						console.log('激励视频 广告显示成功')
					}).catch(err => {
						console.log('激励视频 广告显示失败')
						that.shareVisible = false;
						that.resultStep = 1;
						that.scrollToBottom();
						
						// that.goToResultPage(that.shareMsg.img);
					})
				}).catch(err => {
					console.log('激励视频加载失败');
					that.shareVisible = false;
					that.resultStep = 1;
					that.scrollToBottom();
					
					// that.goToResultPage(that.shareMsg.img);
				})
			},
			// #endif
			
			// #ifdef MP-WEIXIN
			showVideo(){
				const that = this;
				// 用户触发广告后，显示激励视频广告
				if (videoAd) {
				  videoAd.show().catch(() => {
				    // 失败重试
				    videoAd.load()
				      .then(() => videoAd.show())
				      .catch(err => {
				        console.log('激励视频 广告显示失败');
						that.shareVisible = false;
						that.resultStep = 1;
						that.scrollToBottom();
						
						// that.goToResultPage(that.shareMsg.img);
				      })
				  })
				}else{ //每天看激励广告的次数有限，当没调用起广告时直接显示结果
					// 关闭遮罩层
					that.shareVisible = false;
					that.resultStep = 1;
					that.scrollToBottom();
					
					// that.goToResultPage(that.shareMsg.img);
				}
			},
			// #endif

			// #ifdef MP-TOUTIAO

			//头条端-支付测评方法
			async orderPayByTt() {
				/**
				 * 1、走接口获取数据
				 * 2、通过头条接口唤起收银台
				 * 3、通过内置函数通过接口判断当前支付是否成功
				 * 4、成功修改状态，并开始走答题流程
				 */
				const r = await request({
					url: `${config.API}api/tt/order`,
					data: {
						openid: this.openid,
						topic_id: this.id
					}
				});
				const that = this;
				console.log(r)
				if (r.error_code == 0) {
					var _payType = 2;//支付类型 1-微信 2-支付宝
					tt.pay({
						orderInfo: r.data.order_info,
						service: 1,
						_debug: 0,
						getOrderStatus(res) {
							/**
							 * 该方法只针对微信支付做支付状态判断和处理业务逻辑
							 * 支付宝支付不会进入该方法
							 */
							_payType = 1;
							console.log('进入getOrderStatus')
							let {
								out_order_no
							} = res;
							let _url = `${config.API}api/tt/orderQuery?out_order_no=` + out_order_no;
							return new Promise(function(resolve, reject) {
								// 商户前端根据 out_order_no 请求商户后端查询微信支付订单状态
								tt.request({
									url: _url,
									success(res) {
										console.log(res)
										// 商户后端查询的微信支付状态，通知收银台支付结果
										if (res.data.error_code == 0) {
											console.log('ok');
											that.isPay = true;
											that.startAction();
											resolve({
												code: 0
											});
										}
									},
									fail(err) {
										console.log(err)
										reject(err);
									}
								});
							});
						},
						success(res) {
							/**
							 * 支付宝支付成功进入这个函数，处理支付成功后的业务逻辑，
							 * 微信支付成功也有走这个函数，但不用处理业务逻辑。
							 * 微信的业务逻辑在getOrderStatus里处理
							 */
							console.log('支付完回调')
							console.log(res.code)
							if (res.code == 0 && _payType ==2) {
								console.log('ok');
								that.isPay = true;
								that.startAction();
								// resolve({
								// 	code: 0
								// });
							} else {
								console.log(res)
								// return uni.showToast({
								// 	title: '支付失败了·' + res.code,
								// 	icon: 'none'
								// });
							}
						},
						fail(res2) {
							console.log(res2)
							console.log(12233)
							// 调起收银台失败处理逻辑
							return uni.showToast({
								title: '调用支付失败，已安排技术客服处理，请耐心等待!',
								icon: 'none'
							});
						}
					});
				} else {
					console.log('调用支付失败，已安排技术客服处理，请耐心等待')
					return uni.showToast({
						title: '调用支付失败，已安排技术客服处理，请耐心等待',
						icon: 'none'
					});
				}
			},

			//头条端-查看激励视频
			showVideo() {
				const that = this;
				console.log('显示广告');
				videoAd.show().catch(() => {    // 失败重试
				    videoAd
					.load()
					.then(() => videoAd.show())
				        .catch(err => {
				            console.log('激励视频 广告显示失败')
							that.shareVisible = false;
							that.resultStep = 1;
							that.scrollToBottom();
							
							// that.goToResultPage(that.shareMsg.img);
				        })
				});
			},

			//头条获取用户信息
			getTtUserInfo() {
				const that = this;
				tt.authorize({
					scope: "scope.userInfo",
					success(r) {
						console.log(r)
						tt.getUserInfo({
							success(res) {
								console.log(res.userInfo)
								// // 登录
								that.userInfo = res.userInfo;
								that.isAuthUserInfo = true;
								that.isStart = true;
								//存储用户信息
								that.saveUserInfo();
								//在授权完后，需要判断当前测评是否需要支付
								if (that.shareType != 3) {
									that.addOne();
								}

							},
							fail(res) {
								console.log(`getUserInfo 调用失败`);
							}
						});
					},
					fail(rr) {
						return uni.showToast({
							title: '请在设置里打开用户信息',
							icon: 'none'
						});
						
					}
				});
			},
			// #endif
			
		},
		components: {
			UserDialog,
			Result,
			ActionSheet,
			Loading
		},

		// 分享操作
		onShareAppMessage(r) {
			//由于官方声明不会分享回调告知开发者，因此无法针对回调做触发，只能直接显示
			// 关闭遮罩层
			//只有在正常答题完成后才能显示成绩
			if (this.isFinish) {
				this.shareVisible = false;
				this.resultStep = 1;
				this.scrollToBottom();
			}
			let _path = '/pages/detail/index?parentOpenid='+this.openid+'&id='+this.id+'&title='+this.dTitle;
			console.log(_path) 
			// #ifdef MP-QQ||MP-WEIXIN
			return {
				title: this.shareMsg.title,
				// imageUrl: this.resultStep === 1 ? this.poster.src : this.shareMsg.preImg, //当前页显示结果图的分享
				imageUrl:  this.shareMsg.preImg,//新页面跳转结果图的分享
				path: _path, //带上当前用户的openid，分销绑定关系
			}
			// #endif
			// #ifdef MP-TOUTIAO
			if(this.tt_share_template_id != ''){
				return {
					templateId:this.tt_share_template_id,
					path: _path, //带上当前用户的openid，分销绑定关系
				}
			}else{
				return {
					title: this.shareMsg.title,
					imageUrl: this.resultStep === 1 ? this.poster.src : this.shareMsg.preImg,
					path: _path, //带上当前用户的openid，分销绑定关系
				}
			}
			// #endif
		},
		
	}
</script>

<style lang="scss">
	page {
		background-color: #f1f1f1;
	}
</style>

<style lang="scss" scoped>
	$color9: #999;
	$white: #fff;
	$black: #333;
	$blue: #5b78ff;
	$gray: #eee;
	
	.tips-msg {
		padding: 30rpx 0;
		text-align: center;

		text {
			font-size: 28rpx;
			color: $color9;
		}
	}
	
	.qaa-item {
		display: flex;
		padding: 0 30rpx;
		margin-top: 20rpx;
		.qaa-headicon {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			background-color: $white;
			image {
				display: block;
				border-radius: 50%;
				width: 80rpx;
				height: 80rpx;
			}
		}
		.qaa-item-content {
			margin-left: 20rpx;
			background-color: $white;
			border-radius: 16rpx;
			overflow: hidden;
			width: 65%;
			.qaa-item-ct {
				padding: 30rpx;
			}
			image {
				display: block;
				max-width: 100%;
			}
		}
	}
	.qaa-start-desc {
		padding: 30rpx;
		font-size: 32rpx;
		color: #666;
		border-bottom: 2rpx solid #eee;
		&+.qaa-start-btn {
			margin-top: 0;
		}
	}
	
	.qaa-start-btn {
		width: 100%;
		padding: 20rpx 0;
		text-align: center;
		line-height: 1.2;
		background-color: #fff;
		margin-top: 10rpx;
		&::after {
			border: 0;
		}
		text {
			color: $blue;
			font-size: 32rpx;
		}
	}
	
	.qaa-item-right {
		display: flex;
		justify-content: flex-end;
		padding: 0 30rpx;
		margin-top: 20rpx;
		.qaa-itemr-content {
			margin-right: 20rpx;
			background-color: $white;
			border-radius: 16rpx;
			overflow: hidden;
			max-width: 65%;
			display: flex;
			align-items: center;
			.qaa-item-ct {
				padding: 20rpx 30rpx;
			}
			image {
				display: block;
				max-width: 100%;
			}
		}
		.qaa-can-start {
			text-align: center;
			font-size: 32rpx;
			color: $blue;
		}
		.qaa-itemr-headicon {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			background-color: $white;
			image {
				display: block;
				border-radius: 50%;
				width: 80rpx;
				height: 80rpx;
			}
		}
	}
	
	.poster-content {
		position: fixed;
		top: 0;
		left: 200%;
		bottom: 0;
		right: 0;
		z-index: 99;
		background-color: rgba(0, 0, 0, .6);

		&.active {
			left: 0;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		canvas {
			height: auto;
			background-color: #fff;
		}
	}

	.tips-msg2 {
		margin: 30rpx 0;
		text-align: center;

		image {
			width: 40rpx;
			height: 40rpx;
			vertical-align: middle;
		}

		text {
			font-size: 28rpx;
			color: $color9;
			vertical-align: middle;
		}
	}

	.list {
		&:after {
			display: block;
			content: '';
			clear: both;
		}
	}

	.mask {
		position: fixed;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		z-index: 3;
		width: 100%;
		height: 100%;
		display: none;
		flex-direction: column;
		background-color: rgba(0, 0, 0, .6);
		animation: maskShow 300ms;

		&.active {
			display: flex;
		}

		.mask-touch {
			flex: 1;
			width: 100%;
		}

		.mask-content {
			animation: maskContentShow 300ms;

			.mask-user {
				position: relative;

				.mask-user-bg {
					width: 100%;
					display: block;
				}

				.mask-user-content {
					position: absolute;
					top: 0;
					left: 0;
					bottom: 0;
					right: 0;
					text-align: center;
					padding-top: 30rpx;

					.mask-user-img {
						height: 120rpx;
					}

					image {
						border-radius: 50%;
						width: 120rpx;
						height: 120rpx;
						display: inline-block;
					}

					text {
						font-size: 32rpx;
						color: $white;

						.mask-user-strong {
							font-size: 48rpx;
						}
					}
				}
			}
		}
	}

	.mask-btns {
		background-color: $white;
		padding: 10rpx 0 60rpx 0;
		text-align: center;

		.mask-btn {
			width: 68%;
			margin: 0 auto;
			height: 84rpx;
			line-height: 84rpx;
			background: linear-gradient(#5b87ff, #5b78ff);
			border-radius: 10rpx;

			text {
				font-size: 32rpx;
				color: $white;
			}
		}
	}

	.footer-padding {
		height: 120rpx;
	}

	.footer {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 30rpx 0;
		background-color: #fff;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 2;

		&>button,
		&>view {
			height: 84rpx;
			line-height: 84rpx;
			border-radius: 10rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			width: 41%;

			image {
				width: 40rpx;
				margin-right: 10rpx;
			}

			text {
				font-size: 36rpx;
				color: $white;
			}
		}

		&>button {
			background-color: #659fff;
			margin: 0 3% 0 6%;
		}

		&>view {
			background-color: #ef7f1b;
			margin: 0 6% 0 3%;
		}
	}

	.auth-pu {
		position: fixed;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		z-index: 3;
		background-color: rgba(0, 0, 0, .6);
		justify-content: center;
		align-items: center;
		animation: maskShow 300ms;
		display: none;

		&.active {
			display: flex;
		}

		.auth-pu-content {
			background-color: $white;
			width: 80%;

			.auth-pu-text {
				padding: 60rpx 40rpx;
				text-align: center;

				text {
					font-size: 32rpx;
					color: $black;
				}
			}

			.auth-pu-confirm {
				border-top: 1px solid $gray;
				height: 100rpx;
				line-height: 100rpx;
				text-align: center;

				text {
					font-size: 32rpx;
					color: $blue;
				}
			}
		}
	}

	.actionsheet-item {
		background-color: #fff;
		border-radius: 10rpx;
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		margin-bottom: 2px;
		overflow: hidden;
		box-sizing: content-box;

		button {
			height: 100%;
			line-height: 100rpx;
			padding: 0;
			box-sizing: border-box;
		}

		text {
			font-size: 32rpx;
			color: #333;
		}
	}

	@keyframes maskShow {
		from {
			opacity: 0;
		}

		to {
			opacity: 1;
		}
	}

	@keyframes maskContentShow {
		from {
			transform: translateY(100%);
		}

		to {
			transform: translateY(0);
		}
	}
</style>
